package karaokit.com;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

import org.farng.mp3.MP3File;
import org.farng.mp3.TagException;
import org.farng.mp3.id3.ID3v1;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class KaraoKitEngine {

	public enum SearchType {Media, Lyrics}; 

	private static KaraoKitEngine Engine = new KaraoKitEngine();
	public static String KaraoKitDir = "sdcard/KaraokitFiles/";
	//public static final String KaraoKitDirInit = "sdcard/KaraokitFiles/";
	
	private Lyrics mCurLyrics;
	private File mCurMedia;	
	private SearchType mCurBrowseType;

	public static FileFilter MediaFilesFilter  = new FileFilter() {
		public boolean accept(File pathname) {
			String fname = pathname.getName();
			return pathname.isDirectory() ||
			fname.endsWith(".mp3") || fname.endsWith(".wav") || fname.endsWith(".wma") ||
			fname.endsWith(".mid") || fname.endsWith(".xmf") || 
			fname.endsWith(".mxmf") ||
			fname.endsWith(".rtttl") || fname.endsWith(".rtx") || fname.endsWith(".ota");
		}
	};

	public static FileFilter LyricsFilter = new FileFilter() {
		public boolean accept(File pathname) {
			return pathname.isDirectory() ||
			pathname.getName().endsWith(".lrc");
		}
	};

	/*****************************************************************
	 *****************************************************************/
	private KaraoKitEngine() {		
		new File("sdcard/KaraokitFiles/").mkdirs();
	}

	public static KaraoKitEngine GetEngine() {
		return Engine;
	}
	
	public static int FindLyricsFileIndexByCurrentMediaFile(File currentDir)
	{
		File[] files = currentDir.listFiles(KaraoKitEngine.LyricsFilter);
		ID3v1 prop = Engine.getMediaProperties();
		String album = prop.getAlbumTitle();
		String artist = prop.getArtist();
		String title = prop.getSongTitle();
		
		String[] vals = title.split(" ");
		double valsMatched = 0;
		double curPercentage = 0;
		int bestMatch = -1;
		try {
		for (int fileLoc = 0; fileLoc < files.length; ++fileLoc)
		{
			for (int valLoc = 0; valLoc < vals.length; ++valLoc)
			{
					if (files[fileLoc].getCanonicalPath().toLowerCase().contains(vals[valLoc].toLowerCase()))
					{
						valsMatched++;
					}
			}
			if (valsMatched/vals.length > curPercentage)
				{
					curPercentage = valsMatched/vals.length;
					bestMatch = fileLoc;
				}
			if (curPercentage == 1.0)
			{
				return bestMatch;
			}
			
		}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return -1;
	}

	public void loadSong(Context caller, File file) {
		mCurMedia = file; 
		if (!mCurMedia.exists() || !MediaFilesFilter.accept(mCurMedia)) {
			//error: 
			Log.e("Error in opening the sound file in path:" + mCurMedia.getAbsolutePath(), "");
		}
		Intent player = new Intent(caller, Player.class);		
		caller.startActivity(player);
	}

	public void loadLyrics(String path) {
		if (new File(path).exists()) 
			mCurLyrics = new Lyrics(new File(path));
	}

	public void setCurMediaFile(File file) {
		mCurMedia = file;
	}

	public File getCurMediaFile() {
		return mCurMedia;
	}

	public Lyrics getCurLyrics() {
		return mCurLyrics;
	}

	public void setCurLyrics(File lyrics) {
		if (lyrics == null) 
			mCurLyrics = null;

		else
			mCurLyrics = new Lyrics(lyrics);
	}

	public File getNextMediaFile() {
		return getMediaFile(false);
	}

	public File getPrevMediaFile() {
		return getMediaFile(true);
	}

	/*
	 * skips to the next or previous song
	 */
	private File getMediaFile(boolean prev) {
		File curDir = mCurMedia.getParentFile();			
		File[] files = curDir.listFiles(MediaFilesFilter);
		if (files.length == 1) { // no song to skip to
			return mCurMedia;
		}
		int length = files.length;
		for (int i=0; i < length; i++) {
			if (files[i].equals(mCurMedia)) {
				if (prev) {
					if (i==0)
						return files[length-1];
					else
						return files[i-1];
				}
				else { // next song
					if (i==length-1)
						return files[0];
					else
						return files[i+1];
				}				
			}	
		}
		return mCurMedia;
	}

	/*
	 * returns the id tag of the currently loaded song
	 */
	public ID3v1 getMediaProperties() {
		try {
			MP3File mp3file = new MP3File(mCurMedia);
			return mp3file.getID3v1Tag();			
		} catch (IOException e) {
			Log.e("Error opening sound file ", e.getMessage());
		} catch (TagException e) {
			Log.e("Error opening sound file ", e.getMessage());
		}
		return null;
	}

	public boolean isMediaFileLoaded() {
		return (mCurMedia != null);
	}

	public boolean isLyricsLoaded() {
		return (mCurLyrics != null);
	}

	public void startBrowse(Context caller, SearchType type) {
		mCurBrowseType = type;  
		Intent browserIntent = new Intent(caller, FileBrowser.class);
		caller.startActivity(browserIntent);
	}

	// called by the browser
	public void fileSelected(Context caller, File selectedFile, boolean doneBrowsing) {
		switch (mCurBrowseType) {
		case Media:
			mCurMedia = selectedFile;			
			break;
		case Lyrics:
			mCurLyrics = new Lyrics(selectedFile);
			break;
		default: ;
		}
		if (doneBrowsing)
			loadSong(caller, mCurMedia);
	}

	public void setSearchType(SearchType type) {
		mCurBrowseType = type;
	}

	public SearchType getSearchType() {
		return mCurBrowseType;
	}

	public void startSearch(Context caller) {
		Intent searcher = new Intent(caller, Searcher.class);
		caller.startActivity(searcher);
	}
	
	public void startAbout(Context caller) {
		Intent searcher = new Intent(caller, About.class);
		caller.startActivity(searcher);
	}
	
}
